import javax.sound.midi.Soundbank;
import java.math.BigDecimal;

/**
 * @author 03010570
 * @date 2020/06/30
 * describe:    LeetCode:2、两数想加 https://leetcode-cn.com/problems/add-two-numbers/
 */
public class LeetCode_2 {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(9);
        node1.next = new ListNode(8);
        node1.next.next = new ListNode(7);
        ListNode node2 = new ListNode(2);
        node2.next = new ListNode(3);
//        node2.next.next = new ListNode(4);
        ListNode listNode = addTwoNumbers(node1, node2);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode node = new ListNode(0);
        ListNode cur = node;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int x1 = l1 == null ? 0 : l1.val;
            int x2 = l2 == null ? 0 : l2.val;
            int sum = x1 + x2 + carry;

            carry = sum / 10;
            sum = sum % 10;

            cur.next = new ListNode(sum);
            cur = cur.next;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry == 1) {
            cur.next = new ListNode(1);
        }
        return node.next;
    }


}
